/*
 * @Author: Kaze 3243442830@qq.com
 * @Date: 2025-04-07 14:22:35
 * @LastEditors: Kaze 3243442830@qq.com
 * @LastEditTime: 2025-04-07 14:30:17
 * @FilePath: \vue-position-master\src\stores\modules\app.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    mapReady: false,
    mapInstance: null,
    sourceFeaturesInstance: null,
    is2DMode: true,
    map3dInstance: null,
    measureToolsInstance: null
  }),
  
  getters: {
    isMapReady: (state) => state.mapReady,
    hasMapInstance: (state) => !!state.mapInstance,
    hasSourceFeatures: (state) => !!state.sourceFeaturesInstance,
    is3DMode: (state) => !state.is2DMode,
    hasMap3DInstance: (state) => !!state.map3dInstance,
    hasMeasureTools: (state) => !!state.measureToolsInstance
  },
  
  actions: {
    setMapReady(status) {
      this.mapReady = status
    },

    setMapInstance(map) {
      this.mapInstance = map
    },

    setSourceFeaturesInstance(source) {
      this.sourceFeaturesInstance = source
    },

    setIs2DMode(is2D) {
      this.is2DMode = is2D
    },

    setMap3DInstance(map3d) {
      this.map3dInstance = map3d
    },

    setMeasureToolsInstance(tools) {
      this.measureToolsInstance = tools
    },

    // 初始化地图应用
    initMapApp(mapData) {
      if (!mapData) {
        console.error('地图就绪事件数据为空')
        return false
      }

      // 设置地图实例和要素源
      this.mapInstance = mapData.map
      this.sourceFeaturesInstance = mapData.sourceFeatures
      this.is2DMode = mapData.is2D !== undefined ? mapData.is2D : true

      // 确认获取到对象后再设置就绪状态
      if (this.mapInstance && this.sourceFeaturesInstance) {
        this.mapReady = true
        console.log('地图初始化完成:', 
          '- map可用:', !!this.mapInstance, 
          '- source可用:', !!this.sourceFeaturesInstance
        )
        
        // 将地图实例添加到window上，以便测量组件可以查找
        window.mapInstance = this.mapInstance
        
        // 将地图实例存储到map元素上
        try {
          const mapElement = document.getElementById('map')
          if (mapElement) {
            mapElement.__map = this.mapInstance
          }
        } catch (e) {
          console.error('保存地图实例到DOM元素失败:', e)
        }
        
        return true
      } else {
        console.warn('地图就绪但部分对象为null', {
          map: this.mapInstance ? '可用' : '不可用',
          sourceFeatures: this.sourceFeaturesInstance ? '可用' : '不可用'
        })
        return false
      }
    },

    // 重置应用状态
    resetAppState() {
      this.mapReady = false
      this.mapInstance = null
      this.sourceFeaturesInstance = null
      this.is2DMode = true
      this.map3dInstance = null
      this.measureToolsInstance = null
    }
  }
}) 